package com.android.huimeiqupin.fragment.group;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.huimeiqupin.R;
import com.android.huimeiqupin.fragment.BaseLazyFragment;
import com.android.huimeiqupin.model.group.ThematicAGoodsData;
import com.android.huimeiqupin.model.group.ThematicAGoodsDataCallback;
import com.android.huimeiqupin.utils.ConstantsUrl;
import com.android.huimeiqupin.utils.HttpUtils;
import com.android.huimeiqupin.utils.ObjectUtils;
import com.android.huimeiqupin.view.group.VRefreshLayout;
import com.android.huimeiqupin.view.recycleview.CustomLoadMoreView;
import com.android.huimeiqupin.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


/**
 * 9.9元包邮
 */

public class Fragment_FreePostage extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener, View.OnClickListener {


    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    VRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;
    @BindView(R.id.top)
    ImageView top;

    private View rootView;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private FragmentActivity mcontext;
    private int page;
    private View head;
    private ImageView bannerView;
    private AdaptList ta_adapter;
    private ArrayList<ThematicAGoodsData.DataBean.ListDataBean> ta_listdata = new ArrayList<>();
    private GridLayoutManager mGridLayoutManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    public static Fragment_FreePostage newInstance() {
        Fragment_FreePostage fragment = new Fragment_FreePostage();
        return fragment;
    }

    @Override
    protected void initPrepare() {
        ReFreshData();
    }

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            page = 1;
            GetTaListData(page);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }

    }

    private LinearLayoutManager mLayoutManager;

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.inflater = inflater;
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        rootView = inflater.inflate(R.layout.layout_recycle_scmainrefresh, container, false);
        ButterKnife.bind(this, rootView);
        mcontext = getActivity();
        //     mainTopBg.setVisibility(View.GONE);
        initUI();
        return rootView;
    }

    /**
     * 轮播图销毁开启
     */
    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void initUI() {
        head = inflater.inflate(R.layout.item_list_sort_dapai, null, false);
        head.findViewById(R.id.ll_msg).setVisibility(View.GONE);
        bannerView = (ImageView) head.findViewById(R.id.item_list_sort_dapai_img);
        bannerView.setOnClickListener(this);

        ta_adapter = new AdaptList(mcontext, ta_listdata, "");
        ta_adapter.setLoadMoreView(new CustomLoadMoreView());
        ta_adapter.setOnLoadMoreListener(this, mRecyclerView);
        ta_adapter.addHeaderView(head);
        mGridLayoutManager = new GridLayoutManager(mcontext, 2);
        mLayoutManager = new LinearLayoutManager(mcontext);
        mRecyclerView.setLayoutManager(mGridLayoutManager);
        mRecyclerView.setAdapter(ta_adapter);
        mRecyclerView.GetToTop(top, 0);
        ta_adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                ObjectUtils.ToDetailActivity(mcontext, 1, ta_adapter.getItem(position).getId(), "");
            }
        });
    }


    private void ReFreshData() {
        if (mRefreshLayout != null) {
            mRefreshLayout.setBackgroundColor(Color.TRANSPARENT);
            mRefreshLayout.setAutoRefreshDuration(400);
            mRefreshLayout.setRatioOfHeaderHeightToReach(1.5f);
            mRefreshLayout.addOnRefreshListener(new VRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRefreshLayout.refreshComplete();
                                page = 1;
                                GetTaListData(page);
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                    }
                }
            });
        }
    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                GetTaListData(page);
                break;
            case R.id.item_list_sort_dapai_img:
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        page++;
        GetTaListData(page);
    }

    private void GetTaListData(final int page) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.THEMATICGOODSLIST;
        HashMap<String, String> map = new HashMap<>();
        map.put("id", "3");
        map.put("page", page + "");
        if (networkConnected) {
            HttpUtils.get(address, map, new ThematicAGoodsDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(ThematicAGoodsData response, int id) {
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        ThematicAGoodsData.DataBean data = response.getData();
                        if (data == null || !ObjectUtils.listHasData(data.getList())) {
                            if (page == 1) {
                                noData.setVisibility(View.VISIBLE);
                            } else {
                                ta_adapter.loadMoreEnd();
                            }
                            return;
                        }
                        List<ThematicAGoodsData.DataBean.ListDataBean> list = data.getList();
                        if (page == 1) {
                            ta_listdata.clear();
                            ta_listdata.addAll(list);
                            ta_adapter.setNewData(list);
                            ThematicAGoodsData.DataBean.TopicDateBean topic = data.getTopic();
                            if (topic != null && ObjectUtils.listHasData(topic.getThumbs())) {
                                ObjectUtils.photo2(mcontext, topic.getThumbs().get(0), bannerView);
                            }else {
                                ta_adapter.removeHeaderView(head);
                            }
                        } else {
                            ta_listdata.addAll(list);
                            ta_adapter.addData(list);
                            ta_adapter.loadMoreComplete();
                        }
                    } else {
                        if (page == 1) {
                            noData.setVisibility(View.VISIBLE);
                        } else {
                            ta_adapter.loadMoreFail();
                            ObjectUtils.toast(mcontext, response.getMsg());
                        }
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mcontext, "网络连接出现异常");
        }
    }


    public class AdaptList extends BaseMultiItemQuickAdapter<ThematicAGoodsData.DataBean.ListDataBean, BaseViewHolder> {

        public AdaptList(Context context, ArrayList<ThematicAGoodsData.DataBean.ListDataBean> data, String type) {
            super(data);
            addItemType(ConstantsUrl.THEMATICGOODSLISTItemTYPE, R.layout.item_grid_detail_like);
        }

        @Override
        protected void convert(BaseViewHolder holder, ThematicAGoodsData.DataBean.ListDataBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case ConstantsUrl.THEMATICGOODSLISTItemTYPE:
                    holder.getView(R.id.item_grid_open).setVisibility(View.GONE);
                    ((TextView) holder.getView(R.id.item_grid_detail_like_number_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    ObjectUtils.photo2(mcontext, mainlistdata.getImg_src(), (ImageView) holder.getView(R.id.item_grid_detail_like_img));
                    holder.setText(R.id.item_grid_detail_like_title, mainlistdata.getName());
                    holder.setText(R.id.item_grid_detail_like_number_after, mainlistdata.getTeam_price());
                    holder.setText(R.id.item_grid_detail_like_number_before, mainlistdata.getPrice());
//                    holder.setText(R.id.item_grid_detail_like_tuanshu, "已团" + mainlistdata.getSell() + "件");
                    String sellNum = mainlistdata.getSell_num();
                    if (!TextUtils.isEmpty(sellNum) && !sellNum.equals("0")) {
                        holder.setText(R.id.item_grid_detail_like_tuanshu, "已团" + sellNum + "件");
                    }
                    break;
            }
        }
    }

}
